document.addEventListener('DOMContentLoaded', function() {
    // 获取URL参数中的职位ID
    const urlParams = new URLSearchParams(window.location.search);
    const jobId = urlParams.get('id');
    
    // 如果没有职位ID，跳转回首页
    if (!jobId) {
        window.location.href = '../index.html';
        return;
    }
    
    // 获取DOM元素
    const backButton = document.querySelector('.back-button');
    const jobTitleElement = document.querySelector('.job-detail-title');
    const salaryElement = document.querySelector('.job-detail-salary');
    const companyNameElement = document.querySelector('.company-name-detail');
    const companyLocationElement = document.querySelector('.company-location');
    const companyLogoElement = document.getElementById('company-logo');
    const publishTimeElement = document.getElementById('publish-time');
    const jobTypeElement = document.getElementById('job-type');
    const educationElement = document.getElementById('education');
    const experienceElement = document.getElementById('experience');
    const jobDescriptionElement = document.getElementById('job-description');
    const jobRequirementsElement = document.getElementById('job-requirements');
    const jobSkillsElement = document.getElementById('job-skills');
    const favoriteButton = document.querySelector('.favorite-btn');
    const favoriteIcon = document.querySelector('.favorite-icon');
    const applyButton = document.getElementById('apply-button');
    const applyModal = document.getElementById('apply-modal');
    const modalClose = document.querySelector('.modal-close');
    const loginRequiredDiv = document.getElementById('login-required');
    const applyFormDiv = document.getElementById('apply-form');
    const applySuccessDiv = document.getElementById('apply-success');
    const applyLoadingDiv = document.getElementById('apply-loading');
    const goLoginBtn = document.getElementById('go-login-btn');
    const resumeSelect = document.getElementById('resume-select');
    const resumeFile = document.getElementById('resume-file');
    const fileName = document.querySelector('.file-name');
    const submitApplication = document.getElementById('submit-application');
    const closeSuccessBtn = document.getElementById('close-success-btn');
    
    // 职位信息对象
    let jobData = null;
    // 是否已收藏
    let isFavorited = false;
    // 用户简历列表
    let userResumes = [];
    
    // 加载职位详情
    async function loadJobDetail() {
        try {
            // 显示加载状态
            setLoadingState(true);
            
            // 调用API获取职位详情
            jobData = await apiService.getJobDetail(jobId);
            
            // 更新界面
            updateJobDetail(jobData);
            
            // 如果用户已登录，检查是否已收藏该职位
            if (apiService.isLoggedIn()) {
                checkIfFavorited();
            }
            
            // 隐藏加载状态
            setLoadingState(false);
        } catch (error) {
            console.error('加载职位详情失败:', error);
            alert('加载职位详情失败，请稍后再试');
            window.location.href = '../index.html';
        }
    }
    
    // 更新职位详情界面
    function updateJobDetail(data) {
        // 设置页面标题
        document.title = `${data.title} - 工作推荐App`;
        
        // 更新基本信息
        jobTitleElement.textContent = data.title;
        salaryElement.textContent = `薪资: ${data.salary}`;
        companyNameElement.textContent = data.company.name;
        companyLocationElement.textContent = `地址: ${data.company.address}`;
        
        // 设置公司logo
        if (data.company.logo) {
            companyLogoElement.src = data.company.logo;
        }
        
        // 更新元数据
        publishTimeElement.textContent = `发布时间: ${formatDate(data.publishTime)}`;
        jobTypeElement.textContent = `工作类型: ${data.jobType}`;
        educationElement.textContent = `学历要求: ${data.education}`;
        experienceElement.textContent = `工作经验: ${data.experience}`;
        
        // 更新职位描述
        jobDescriptionElement.innerHTML = formatContent(data.description);
        
        // 更新职位要求
        jobRequirementsElement.innerHTML = formatContent(data.requirements);
        
        // 更新技能要求
        jobSkillsElement.innerHTML = '';
        data.skills.forEach(skill => {
            const skillTag = document.createElement('span');
            skillTag.className = 'tag';
            skillTag.textContent = skill;
            jobSkillsElement.appendChild(skillTag);
        });
    }
    
    // 设置加载状态
    function setLoadingState(isLoading) {
        // 这里可以添加加载指示器
        console.log(isLoading ? '加载中...' : '加载完成');
    }
    
    // 格式化日期
    function formatDate(dateString) {
        const date = new Date(dateString);
        return date.toLocaleDateString('zh-CN', {
            year: 'numeric',
            month: 'long',
            day: 'numeric'
        });
    }
    
    // 格式化内容，将\\n转换为HTML段落
    function formatContent(content) {
        if (!content) return '';
        
        // 将换行符转换为段落
        return content.split('\n')
            .filter(paragraph => paragraph.trim() !== '')
            .map(paragraph => `<p>${paragraph}</p>`)
            .join('');
    }
    
    // 检查是否已收藏该职位
    async function checkIfFavorited() {
        try {
            const favorites = await apiService.getFavorites();
            isFavorited = favorites.some(fav => fav.job_id === jobId);
            
            updateFavoriteButton();
        } catch (error) {
            console.error('检查收藏状态失败:', error);
        }
    }
    
    // 更新收藏按钮状态
    function updateFavoriteButton() {
        if (isFavorited) {
            favoriteButton.classList.add('active');
            favoriteIcon.src = '../images/favorite-filled.svg';
        } else {
            favoriteButton.classList.remove('active');
            favoriteIcon.src = '../images/favorite-outline.svg';
        }
    }
    
    // 切换收藏状态
    async function toggleFavorite() {
        if (!apiService.isLoggedIn()) {
            // 如果未登录，显示登录提示
            showLoginModal();
            return;
        }
        
        try {
            if (isFavorited) {
                // 取消收藏
                await apiService.unfavoriteJob(jobId);
                isFavorited = false;
            } else {
                // 添加收藏
                await apiService.favoriteJob(jobId);
                isFavorited = true;
            }
            
            // 更新按钮状态
            updateFavoriteButton();
        } catch (error) {
            console.error('操作收藏失败:', error);
            alert('操作失败，请稍后再试');
        }
    }
    
    // 显示申请职位弹窗
    function showApplyModal() {
        // 检查用户是否已登录
        if (!apiService.isLoggedIn()) {
            // 显示登录提示
            loginRequiredDiv.style.display = 'block';
            applyFormDiv.style.display = 'none';
            applySuccessDiv.style.display = 'none';
            applyLoadingDiv.style.display = 'none';
        } else {
            // 显示申请表单
            loginRequiredDiv.style.display = 'none';
            applyFormDiv.style.display = 'block';
            applySuccessDiv.style.display = 'none';
            applyLoadingDiv.style.display = 'none';
            
            // 加载用户简历
            loadUserResumes();
        }
        
        // 显示弹窗
        applyModal.classList.add('show');
    }
    
    // 关闭申请职位弹窗
    function closeApplyModal() {
        applyModal.classList.remove('show');
    }
    
    // 加载用户简历
    async function loadUserResumes() {
        try {
            userResumes = await apiService.getUserResumes();
            
            // 更新简历下拉列表
            resumeSelect.innerHTML = '<option value="">--请选择简历--</option>';
            
            userResumes.forEach(resume => {
                const option = document.createElement('option');
                option.value = resume.id;
                option.textContent = resume.name;
                resumeSelect.appendChild(option);
            });
        } catch (error) {
            console.error('加载简历失败:', error);
        }
    }
    
    // 提交职位申请
    async function submitJobApplication() {
        // 获取选择的简历ID
        const resumeId = resumeSelect.value;
        
        // 获取上传的文件
        const file = resumeFile.files[0];
        
        // 获取求职信
        const coverLetter = document.getElementById('cover-letter').value;
        
        // 验证表单
        if (!resumeId && !file) {
            alert('请选择简历或上传新简历');
            return;
        }
        
        try {
            // 显示加载状态
            loginRequiredDiv.style.display = 'none';
            applyFormDiv.style.display = 'none';
            applySuccessDiv.style.display = 'none';
            applyLoadingDiv.style.display = 'block';
            
            let finalResumeId = resumeId;
            
            // 如果上传了新简历，先上传
            if (file) {
                const formData = new FormData();
                formData.append('resume', file);
                formData.append('name', file.name);
                
                const uploadResult = await apiService.uploadResume(formData);
                finalResumeId = uploadResult.id;
            }
            
            // 提交申请
            await apiService.applyForJob(jobId, finalResumeId, coverLetter);
            
            // 显示成功消息
            loginRequiredDiv.style.display = 'none';
            applyFormDiv.style.display = 'none';
            applySuccessDiv.style.display = 'block';
            applyLoadingDiv.style.display = 'none';
        } catch (error) {
            console.error('提交申请失败:', error);
            alert('提交申请失败，请稍后再试');
            
            // 返回表单
            loginRequiredDiv.style.display = 'none';
            applyFormDiv.style.display = 'block';
            applySuccessDiv.style.display = 'none';
            applyLoadingDiv.style.display = 'none';
        }
    }
    
    // 显示登录弹窗
    function showLoginModal() {
        // 这里可以跳转到登录页面或显示登录弹窗
        window.location.href = `../pages/login.html?redirect=${encodeURIComponent(window.location.href)}`;
    }
    
    // 返回上一页
    function goBack() {
        window.history.back();
    }
    
    // 更新文件名显示
    function updateFileName() {
        const file = resumeFile.files[0];
        if (file) {
            fileName.textContent = file.name;
        } else {
            fileName.textContent = '未选择文件';
        }
    }
    
    // 添加事件监听器
    backButton.addEventListener('click', goBack);
    favoriteButton.addEventListener('click', toggleFavorite);
    applyButton.addEventListener('click', showApplyModal);
    modalClose.addEventListener('click', closeApplyModal);
    goLoginBtn.addEventListener('click', showLoginModal);
    submitApplication.addEventListener('click', submitJobApplication);
    closeSuccessBtn.addEventListener('click', closeApplyModal);
    resumeFile.addEventListener('change', updateFileName);
    
    // 点击模态框背景关闭模态框
    applyModal.addEventListener('click', function(event) {
        if (event.target === applyModal) {
            closeApplyModal();
        }
    });
    
    // 加载职位详情
    loadJobDetail();
}); 